/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;

/**
 *
 * @author Trang
 */
public class FileUploadAction extends ActionSupport
implements ServletRequestAware{
    private File userImage;
    private String userImageContentType;
    private String userImageFileName;
    private HttpServletRequest servletRequest;
    
    
    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
    }
    
     @Action(value = "action1", results = {
        @Result(name = "success", location = "/SuccessUserImage.jsp")
    })
     public String execute() {
        try {
            String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
            String newPath = filePath.substring(0, filePath.length()-10) + "web/image/";
            System.out.println("Server path:" + newPath);
            File fileToCreate = new File(newPath, this.userImageFileName);
 
            FileUtils.copyFile(this.userImage, fileToCreate);
            System.out.println(fileToCreate.getAbsolutePath());
           
        } catch (Exception e) {
            e.printStackTrace();
            addActionError(e.getMessage());
 
            return INPUT;
        }
        return SUCCESS;
    }
     @Action()
    /**
     * @return the userImage
     */
    public File getUserImage() {
        return userImage;
    }

    /**
     * @param userImage the userImage to set
     */
    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }

    /**
     * @return the userImageContentType
     */
    public String getUserImageContentType() {
        return userImageContentType;
    }

    /**
     * @param userImageContentType the userImageContentType to set
     */
    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }

    /**
     * @return the userImageFileName
     */
    public String getUserImageFileName() {
        return userImageFileName;
    }

    /**
     * @param userImageFileName the userImageFileName to set
     */
    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }
    
}
